function treeFilter(node, cb) {
  node = node.filter((child) => {
    if (child.children) child.children = treeFilter(child.children, cb)

    return cb(child)
  })

  return node
}

function treeFind(tree, cb) {
  let result
  eachTree(tree, (item) => {
    const isMatch = cb(item)
    if (isMatch) result = item

    return isMatch
  })

  return result
}

/**
 * 树形结构遍历
 * @param {Array} tree 树形结构数据
 * @param {Function} callback 回调函数如果返回真，停止遍历
 */
function eachTree(tree, cb) {
  for (let i = 0; i < tree.length; i++) {
    let item = tree[i]
    let result

    if (cb) result = cb(item)

    if (result !== true && item.children) result = eachTree(item.children, cb)

    if (result === true) return result
  }
}

/**
 * 扁平化数据树形结构
 * @param {Array} arr 数组
 * @param {Function} callback
 * @returns
 */
function flatArrayToTree(arr, cb) {
  // 创建一个空的对象，用于存储节点信息
  const map = {}
  const tree = []
  const handle = (item) => {
    if (cb) return cb(item)
    else return item
  }

  // 将数组转换为映射，方便查找父节点
  arr.forEach((item) => {
    const newItem = handle(item)
    map[item.id] = { ...newItem, children: [] }
  })

  // 遍历数组，将节点添加到树中
  arr.forEach((item) => {
    const treeItem = map[item.id]

    if (item.parentId) {
      const parent = map[item.parentId]

      if (parent) {
        parent.children.push(treeItem)
      } else {
        tree.push(treeItem)
      }
    } else {
      tree.push(treeItem)
    }
  })

  return tree
}

module.exports = {
  treeFilter,
  treeFind,
  eachTree,
  flatArrayToTree,
}
